package com.witmore.neutron.ai.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.common.response.PageInfo;
import com.jk.common.response.ResponsePageResult;
import com.jk.common.response.ResponseResult;
import com.jk.common.utils.PasswordUtil;
import com.witmore.neutron.ai.db.entity.ProviderProfileDO;
import com.witmore.neutron.ai.db.entity.UserDO;
import com.witmore.neutron.ai.db.entity.UserProviderDO;
import com.witmore.neutron.ai.db.mapper.ProviderProfileMapper;
import com.witmore.neutron.ai.db.mapper.UserMapper;
import com.witmore.neutron.ai.db.mapper.UserProviderMapper;
import com.witmore.neutron.ai.web.apiv2.controller.vo.*;
import com.witmore.neutron.ai.web.controller.vo.UserSession;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.service.ProviderProfileService;
import com.witmore.neutron.ai.web.service.UserRoleBindingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务商信息服务实现
 * Author: 豆子高
 * Date: 2025/01/XX
 */
@Slf4j
@Service
public class ProviderProfileServiceImpl implements ProviderProfileService {

    @Autowired
    private ProviderProfileMapper providerProfileMapper;

    @Autowired
    private UserProviderMapper userProviderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleBindingService userRoleBindingService;


    @Override
    @Transactional
    public ResponseResult<Void> createProviderByUser(ProviderProfileUserCreateParam createParam) {
        try {
            // 获取当前登录用户信息
            UserSession userSession = GlobalAccountSession.getUserInfo();
            if (userSession == null) {
                return ResponseResult.fail(401, "用户未登录");
            }

            // 检查服务商名称是否已存在
            ProviderProfileDO existingProvider = providerProfileMapper.selectOne(
                    new LambdaQueryWrapper<ProviderProfileDO>()
                            .eq(ProviderProfileDO::getProviderName, createParam.getProviderName())
            );
            if (existingProvider != null) {
                return ResponseResult.fail(400, "服务商名称已存在");
            }

            // 创建服务商信息，状态为待审核且禁用
            ProviderProfileDO providerProfileDO = new ProviderProfileDO();
            providerProfileDO.setProviderName(createParam.getProviderName());
            providerProfileDO.setProviderDesc(createParam.getProviderDesc());
            providerProfileDO.setProviderLogo(createParam.getProviderLogo());
            providerProfileDO.setBusinessLicense(createParam.getBusinessLicense());

            providerProfileDO.setUserId(userSession.getId());
            providerProfileDO.setContactPerson(userSession.getUserName());
            providerProfileDO.setContactPhone(userSession.getUserPhone());
            providerProfileDO.setCertificationStatus(0); // 待审核
            providerProfileDO.setStatus(0); // 禁用状态
            providerProfileDO.setAgentCount(0);
            providerProfileDO.setTotalUsageCount(0);
            providerProfileDO.setCreateTime(LocalDateTime.now());
            providerProfileDO.setUpdateTime(LocalDateTime.now());
            //TODO
            providerProfileDO.setSessionTotalTimes(0);
            providerProfileDO.setSessionRemainingTimes(0);

            int insertResult = providerProfileMapper.insert(providerProfileDO);
            if (insertResult <= 0) {
                return ResponseResult.fail(500, "创建服务商失败");
            }

            return ResponseResult.success();
        } catch (Exception e) {
            log.error("用户创建服务商异常", e);
            return ResponseResult.fail(500, "创建服务商异常：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> createProviderByAdmin(ProviderProfileAdminCreateParam createParam) {
        try {
            // 检查服务商名称是否已存在
            ProviderProfileDO existingProvider = providerProfileMapper.selectOne(
                    new LambdaQueryWrapper<ProviderProfileDO>()
                            .eq(ProviderProfileDO::getProviderName, createParam.getProviderName())
            );
            if (existingProvider != null) {
                return ResponseResult.fail(400, "服务商名称已存在");
            }

            // 检查联系人手机号是否已存在用户
            UserDO existingUser = userMapper.selectOne(
                    new LambdaQueryWrapper<UserDO>()
                            .eq(UserDO::getUserPhone, createParam.getContactPhone())
            );

            UserDO userDO;
            if (existingUser != null) {
                // 用户已存在，直接使用
                userDO = existingUser;
            } else {
                // 创建新用户
                userDO = new UserDO();
                userDO.setUserName(createParam.getContactPerson());
                userDO.setUserPhone(createParam.getContactPhone());
                userDO.setPassword(PasswordUtil.hashPassword("123456")); // 默认密码
                userDO.setActiveStatus((byte) 1); // 已激活
                userDO.setIsSuperAdmin(false);
                userDO.setCreateTime(LocalDateTime.now());
                userDO.setUpdateTime(LocalDateTime.now());
                userDO.setRegisterTime(LocalDateTime.now());
                // TODO
                userDO.setSessionTotalTimes(0);
                userDO.setSessionRemainingTimes(0);
                userMapper.insert(userDO);
            }

            // 创建服务商信息
            ProviderProfileDO providerProfileDO = new ProviderProfileDO();
            BeanUtils.copyProperties(createParam, providerProfileDO);
            providerProfileDO.setUserId(userDO.getId());
            // 已认证
            providerProfileDO.setCertificationStatus(1);
            // 正常状态
            providerProfileDO.setStatus(1);
            providerProfileDO.setAgentCount(0);
            providerProfileDO.setTotalUsageCount(0);
            providerProfileDO.setCreateTime(LocalDateTime.now());
            providerProfileDO.setUpdateTime(LocalDateTime.now());

            providerProfileMapper.insert(providerProfileDO);

            // 创建用户与服务商关联关系，设置为负责人
            createProviderOwnerRelation(providerProfileDO.getId(), userDO.getId(), "管理员创建的服务商负责人");

            // 为用户绑定服务商管理员角色
            try {
                userRoleBindingService.bindServiceProviderAdminRole(userDO.getId().longValue(), providerProfileDO.getId().longValue());
                log.info("成功为用户{}绑定服务商{}管理员角色", userDO.getId(), providerProfileDO.getId());
            } catch (Exception e) {
                log.error("为用户{}绑定服务商{}管理员角色失败", userDO.getId(), providerProfileDO.getId(), e);
                // 角色绑定失败不影响服务商创建，只记录日志
            }

            return ResponseResult.success();
        } catch (Exception e) {
            log.error("管理员创建服务商异常", e);
            throw new RuntimeException("创建服务商异常：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult<Void> updateProvider(ProviderProfileUpdateParam updateParam) {
        try {
            ProviderProfileDO existingProvider = providerProfileMapper.selectById(updateParam.getId());
            if (existingProvider == null) {
                return ResponseResult.fail(404, "服务商不存在");
            }

            ProviderProfileDO updateDO = new ProviderProfileDO();
            BeanUtils.copyProperties(updateParam, updateDO);
            updateDO.setUpdateTime(LocalDateTime.now());

            int updateResult = providerProfileMapper.updateById(updateDO);
            if (updateResult <= 0) {
                return ResponseResult.fail(500, "更新服务商失败");
            }

            return ResponseResult.success();
        } catch (Exception e) {
            log.error("更新服务商异常", e);
            return ResponseResult.fail(500, "更新服务商异常：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult<Void> deleteProvider(Integer id) {
        try {
            ProviderProfileDO existingProvider = providerProfileMapper.selectById(id);
            if (existingProvider == null) {
                return ResponseResult.fail(404, "服务商不存在");
            }

            // 检查是否有关联的员工
            Long employeeCount = userProviderMapper.selectCount(
                    new LambdaQueryWrapper<UserProviderDO>()
                            .eq(UserProviderDO::getProviderId, id)
            );
            if (employeeCount > 0) {
                return ResponseResult.fail(400, "该服务商下存在员工，无法删除");
            }

            providerProfileMapper.deleteById(id);

            return ResponseResult.success();
        } catch (Exception e) {
            log.error("删除服务商异常", e);
            return ResponseResult.fail(500, "删除服务商异常：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult<ProviderProfileDO> getProviderById(Integer id) {
        try {
            ProviderProfileDO providerProfileDO = providerProfileMapper.selectById(id);
            if (providerProfileDO == null) {
                return ResponseResult.fail(404, "服务商不存在");
            }
            return ResponseResult.success(providerProfileDO);
        } catch (Exception e) {
            log.error("查询服务商详情异常", e);
            return ResponseResult.fail(500, "查询服务商详情异常：" + e.getMessage());
        }
    }

    @Override
    public Page<ProviderProfileDO> getProviderPage(ProviderProfileQueryParam queryParam) {

        LambdaQueryWrapper<ProviderProfileDO> queryWrapper = new LambdaQueryWrapper<ProviderProfileDO>()
                .like(StringUtils.isNotBlank(queryParam.getProviderName()),
                        ProviderProfileDO::getProviderName, queryParam.getProviderName())
                .eq(queryParam.getCertificationStatus() != null,
                        ProviderProfileDO::getCertificationStatus, queryParam.getCertificationStatus())
                .eq(queryParam.getStatus() != null,
                        ProviderProfileDO::getStatus, queryParam.getStatus())
                .orderByDesc(ProviderProfileDO::getCreateTime);

        return providerProfileMapper.selectPage(new Page<>(queryParam.getPage(), queryParam.getSize()), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult<Void> auditProvider(ProviderAuditParam auditParam) {
        try {
            ProviderProfileDO existingProvider = providerProfileMapper.selectById(auditParam.getId());
            if (existingProvider == null) {
                return ResponseResult.fail(404, "服务商不存在");
            }

            if (existingProvider.getCertificationStatus() != 0) {
                return ResponseResult.fail(400, "该服务商已审核，无法重复审核");
            }

            if (auditParam.getCertificationStatus() != 1 && auditParam.getCertificationStatus() != 2) {
                return ResponseResult.fail(400, "认证状态参数错误");
            }

            ProviderProfileDO updateDO = new ProviderProfileDO();
            updateDO.setId(auditParam.getId());
            updateDO.setCertificationStatus(auditParam.getCertificationStatus());
            updateDO.setUpdateTime(LocalDateTime.now());

            providerProfileMapper.updateById(updateDO);

            // 认证成功的企业需要创建员工关系
            if (auditParam.getCertificationStatus() == 1) {
                // 创建服务商创建者的员工关系（设置为负责人）
                createProviderOwnerRelation(existingProvider.getId(), existingProvider.getUserId(), "审核通过后自动创建的负责人关系");

                // 为用户绑定服务商管理员角色
                try {
                    userRoleBindingService.bindServiceProviderAdminRole(existingProvider.getUserId().longValue(), existingProvider.getId().longValue());
                    log.info("成功为用户{}绑定服务商{}管理员角色", existingProvider.getUserId(), existingProvider.getId());
                } catch (Exception e) {
                    log.error("为用户{}绑定服务商{}管理员角色失败", existingProvider.getUserId(), existingProvider.getId(), e);
                    // 角色绑定失败不影响审核流程，只记录日志
                }

                // 审核通过后启用服务商
                ProviderProfileDO enableProvider = new ProviderProfileDO();
                enableProvider.setId(auditParam.getId());
                enableProvider.setStatus(1); // 启用
                enableProvider.setUpdateTime(LocalDateTime.now());
                providerProfileMapper.updateById(enableProvider);
            }

            return ResponseResult.success();
        } catch (Exception e) {
            log.error("审核服务商异常", e);
            throw new RuntimeException("审核服务商异常：" + e.getMessage());
        }
    }

    @Override
    public ResponsePageResult<ProviderEmployeeResult> getProviderEmployeePage(ProviderEmployeeQueryParam queryParam) {

        LambdaQueryWrapper<UserProviderDO> queryWrapper = new LambdaQueryWrapper<UserProviderDO>()
                .eq(queryParam.getProviderId() != null,
                        UserProviderDO::getProviderId, queryParam.getProviderId())
                .eq(queryParam.getIsOwner() != null,
                        UserProviderDO::getIsOwner, queryParam.getIsOwner())
                .eq(queryParam.getStatus() != null,
                        UserProviderDO::getStatus, queryParam.getStatus())
                .orderByDesc(UserProviderDO::getCreateTime);

        Page<UserProviderDO> userProviderPage = userProviderMapper.selectPage(new Page<>(queryParam.getPage(), queryParam.getSize()), queryWrapper);

        // 转换为结果对象并补充服务商信息
        List<ProviderEmployeeResult> resultList = userProviderPage.getRecords().stream()
                .map(this::convertToEmployeeResult)
                .collect(Collectors.toList());

        return ResponsePageResult.success(resultList, new PageInfo(userProviderPage.getCurrent(), userProviderPage.getSize(), userProviderPage.getTotal(), userProviderPage.getPages()));
    }

    @Override
    public ProviderEmployeeResult getUserProviderInfo(Integer userId) {
        try {
            // 查询用户关联的服务商信息（优先返回负责人身份的服务商）
            UserProviderDO userProviderDO = userProviderMapper.selectOne(
                    new LambdaQueryWrapper<UserProviderDO>()
                            .eq(UserProviderDO::getUserId, userId)
                            .eq(UserProviderDO::getStatus, 1) // 只查询启用状态的关系
                            .orderByDesc(UserProviderDO::getIsOwner) // 优先返回负责人身份
                            .orderByDesc(UserProviderDO::getCreateTime) // 然后按创建时间降序
                            .last("LIMIT 1") // 只取第一条
            );

            if (userProviderDO == null) {
                return null; // 用户没有关联任何服务商
            }

            return convertToEmployeeResult(userProviderDO);
        } catch (Exception e) {
            log.error("查询用户服务商信息异常，userId: {}", userId, e);
            return null;
        }
    }

    private ProviderEmployeeResult convertToEmployeeResult(UserProviderDO userProviderDO) {
        ProviderEmployeeResult result = new ProviderEmployeeResult();
        BeanUtils.copyProperties(userProviderDO, result);

        // 查询服务商详细信息
        ProviderProfileDO providerProfile = providerProfileMapper.selectById(userProviderDO.getProviderId());
        if (providerProfile != null) {
            result.setProviderName(providerProfile.getProviderName());
        }

        return result;
    }

    /**
     * 创建服务商负责人关系的公用方法
     *
     * @param providerId  服务商ID
     * @param userId      用户ID
     * @param description 关系描述
     */
    private void createProviderOwnerRelation(Integer providerId, Integer userId, String description) {
        try {
            // 检查是否已存在关联关系
            UserProviderDO existingRelation = userProviderMapper.selectOne(
                    new LambdaQueryWrapper<UserProviderDO>()
                            .eq(UserProviderDO::getUserId, userId)
                            .eq(UserProviderDO::getProviderId, providerId)
            );

            if (existingRelation != null) {
                // 如果已存在关系，更新为负责人
                existingRelation.setIsOwner(1);
                existingRelation.setStatus(1);
                existingRelation.setDescription(description);
                existingRelation.setUpdateTime(LocalDateTime.now());
                userProviderMapper.updateById(existingRelation);

            } else {
                // 创建新的关联关系
                UserProviderDO userProviderDO = new UserProviderDO();
                userProviderDO.setUserId(userId);
                userProviderDO.setProviderId(providerId);
                userProviderDO.setIsOwner(1); // 是负责人
                userProviderDO.setSessionCount(0);
                userProviderDO.setStatus(1); // 启用
                userProviderDO.setDescription(description);
                userProviderDO.setCreateTime(LocalDateTime.now());
                userProviderDO.setUpdateTime(LocalDateTime.now());
                userProviderMapper.insert(userProviderDO);
            }
        } catch (Exception e) {
            log.error("创建服务商负责人关系异常", e);
            throw new RuntimeException("创建服务商负责人关系异常：" + e.getMessage());
        }
    }
}
